package creador;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class OfficeUtil {

	public static void replaceSubStringInWord(String fileName, String textToReplace, String newText) {
		ActiveXComponent word = new ActiveXComponent("Word.Application");
		word.setProperty("Visible", new Variant(false));

		Dispatch documents = word.getProperty("Documents").toDispatch();
		Dispatch document = Dispatch.call(documents, "Open", fileName).toDispatch();

		Dispatch selection = word.getProperty("Selection").toDispatch();
		Dispatch find = Dispatch.call(selection, "Find").toDispatch();
		Dispatch.put(find, "Text", textToReplace);
		Dispatch.call(find, "Execute");
		Dispatch.put(selection, "Text", newText);
		Dispatch.call(selection, "MoveDown");

		selection = word.getProperty("Selection").toDispatch();
		find = Dispatch.call(selection, "Find").toDispatch();
		Dispatch.put(find, "Text", textToReplace);
		Dispatch.call(find, "Execute");
		Dispatch.put(selection, "Text", newText);
		Dispatch.call(selection, "MoveDown");
		
		Dispatch.call(word, "WordBasic").getDispatch();
		Dispatch.call(document, "Close", new Variant(true));

		// Quit Word.
		word.invoke("Quit", new Variant(false));
	}

}
